package com.example.lending.ViewModel;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.SavedStateHandle;

import com.example.lending.Model.User;
import com.example.lending.R;
import com.example.lending.ViewModel.Repository.UserRepository;

import java.util.List;

public class UserViewModel extends AndroidViewModel {
    private UserRepository userRepository;
    SavedStateHandle handle;
    String username_key;
    String password_key;
    String shp_name;
    int isLogin;//用来判断是否登陆过账号了，0是登陆过了，直接进去，1是还需要再登录
    public UserViewModel(@NonNull Application application) {
        super(application);
        userRepository = new UserRepository(application);
    }
    public UserViewModel(@NonNull Application application,SavedStateHandle handle){
        super(application);
        this.handle=handle;
        userRepository = new UserRepository(application);
        if(handle.contains(username_key)&&handle.contains(password_key)){
            load();
        }
        username_key=getApplication().getResources().getString(R.string.data_username_key);
        password_key=getApplication().getResources().getString(R.string.data_password_key);
        shp_name=getApplication().getResources().getString(R.string.shp_name);

    }
    //login没写，
    public LiveData<String> getUsername(){
        return handle.getLiveData(username_key);
    }
    public LiveData<String> getPassword(){
        return handle.getLiveData(password_key);
    }
    public List<User> findUsers(String patterns){
        return userRepository.findUsers(patterns);
    }

    void load(){ //
        SharedPreferences shp = getApplication().getSharedPreferences(shp_name, Context.MODE_PRIVATE);
        SharedPreferences sp=getApplication().getSharedPreferences("user",getApplication().MODE_PRIVATE);
        String username=getApplication().getSharedPreferences("user", Context.MODE_PRIVATE).getString("username","");
        String password=findUserWithPattern(username).getValue().get(0).getPassword();
        handle.set(username_key,username);
        handle.set(password_key,password);
    }

    public void insertUsers(User... users){userRepository.insertUsers(users);}
    public void updataUsers(User... users){userRepository.updataUsers(users);}
    public void deleteUsers(User... users){userRepository.deleteUsers(users);}
    public void deleteAllUsers(Void... voids){userRepository.deleteAllUsers();}
    public LiveData<List<User>> getAllUserLive(){return userRepository.getAllUserLive();}
    public LiveData<List<User>>findUserWithPattern(String pattern){
        return userRepository.findUserWithPattern(pattern);
    }

    public int getIsLogin() {
        return isLogin;
    }

    public void setIsLogin(int isLogin) {
        this.isLogin = isLogin;
    }
}
